package net.daum.webtoon.android;

import java.util.ArrayList;

import net.daum.webtoon.android.jibx.data.FileManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

	public static String TAG = MainActivity.class.getSimpleName();
	private WebView mView;
	private final String TOONRSS = "http://cartoon.media.daum.net/webtoon/rss/";
	private final String TOONDOMAIN = "http://cartoon.media.daum.net/";
	public static ArrayList<WebToonInfo> gInfo;
	public int mPageNum;
	public int mTotalCount;

	public static ArrayList<WebToonInfo> getGInfo(Context aCtx) {
		if (gInfo == null || gInfo.isEmpty() || gInfo.size() < 1) {
			gInfo = (ArrayList<WebToonInfo>) FileManager.loadObj(aCtx, FileManager.WEEKLISTPATH, FileManager.makeFileNameByDate() + ".obj");
		}
		
		return gInfo;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mPageNum = 1;
		mTotalCount = 0;
		gInfo = (ArrayList<WebToonInfo>) FileManager.loadObj(getApplicationContext(), FileManager.WEEKLISTPATH, FileManager.makeFileNameByDate()
				+ ".obj");

		if (gInfo == null || gInfo.isEmpty())
			gInfo = new ArrayList<WebToonInfo>();
		else {
			startActivity(new Intent(MainActivity.this, WebToonListActivity.class).putExtra("ISSVAED", true));
			finish();
		}
		mView = (WebView) findViewById(R.id.main_view);
		mView.setWebViewClient(new WebViewClientClass());
		mView.getSettings().setJavaScriptEnabled(true);
		mView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
		mView.getSettings().setLoadsImagesAutomatically(false);
//		mView.loadUrl("http://cartoon.media.daum.net/webtoon/select#pageNo=" + mPageNum++);
//		mView.setVisibility(View.GONE);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		mView.loadUrl("file:// ");

		super.onResume();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void xmlOnClick(View v) {

	}

	private class WebViewClientClass extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub

			view.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
//			super.onPageFinished(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
//			boolean isHave = false;
//			boolean isView = false;
//			String lName = "";
//			String[] lUrlString = url.split("/");
//			for (String lStr : lUrlString) {
//				if (isHave) {
//					isView = true;
//					lName = lStr;
//					Log.d(TAG, "toon Name == " + lStr);
//				}
//				if (lStr.equalsIgnoreCase("view"))
//					isHave = true;
//
//			}
//
//			if (isView) {
//				view.loadUrl(TOONRSS + lName);
//				return;
//			}
			super.onPageStarted(view, url, favicon);
		}

	}

	private class MyJavaScriptInterface {

		public void showHTML(String html) {
			boolean isValidPage = false;
			int isLastCount = gInfo.size();
			if (mView.getUrl().toString().equalsIgnoreCase("http://cartoon.media.daum.net/webtoon/select#pageNo=" + mPageNum))
				isValidPage = true;

			if (html.length() < 5000 && !isValidPage) {

				mView.loadUrl("http://cartoon.media.daum.net/webtoon/select#pageNo=" + mPageNum);
				return;
			}

			String[] htmlLine = html.split("txt_count");
			try {
				if (mTotalCount == 0)
					mTotalCount = Integer.parseInt((htmlLine[1].split("<em class=\"num\">")[1].replace("<", "\n").split("\n")[0]));
			} catch (Exception e) {

			}
//			for (String lStr : htmlLine) {
			for (String lStr2 : html.split("<span class=\"thumb\">")) {
				if (lStr2.trim().startsWith("<a href=\"/webtoon/view/")) {
					WebToonInfo info = new WebToonInfo(lStr2.trim());
					gInfo.add(info);
				}
//				}
			}

			Log.d(TAG, "http://cartoon.media.daum.net/webtoon/select#pageNo=" + mPageNum);
			if (mTotalCount > 0 && gInfo.size() >= mTotalCount && (mPageNum * 30) >= mTotalCount) {
				startActivity(new Intent(MainActivity.this, WebToonListActivity.class));
				finish();
			} else {
				if (isLastCount < gInfo.size() && isValidPage) {
					mView.stopLoading();
					mPageNum++;
				}
				onResume();
			}
		}
	}

}
